﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Core;
using EPiServer.DynamicContent;
using System.Text.RegularExpressions;
using EPiServer.Core.Html;

namespace EPiSugar.Markup
{
    //TODO:check licensing issues for code from episervercms.dll
    public class TextServices
    {
        static TextServices()
        {
            StringBuilder regexPattern = new StringBuilder(@"<span[\s\W\w]*?classid=""");
            regexPattern.Append(DynamicContentFactory.Instance.DynamicContentId.ToString());
            regexPattern.Append(@"""[\s\W\w]*?</span>");
            dynamicContent = new Regex(regexPattern.ToString(), RegexOptions.IgnoreCase | RegexOptions.Multiline);
        }

        private static Regex dynamicContent;

        /// <returns>Returns the preview text for the specified PageData</returns>
        /// <remarks>The preview text is primarily created from the MainIntro property if it exists, 
        /// otherwise parts of the MainBody property are being used. 
        /// If neither a MainIntro nor a MainBody property exists, the preview will not be shown. 
        /// The length of the preview text is defined in <code>PreviewTextLength</code></remarks>
        public static string GetPreviewText(PageData page, int PreviewTextLength)
        {
            if (PreviewTextLength <= 0)
            {
                return string.Empty;
            }

            string previewText = page["MainIntro"] as string;
            if (!String.IsNullOrEmpty(previewText))
            {
                return StripPreviewText(previewText, PreviewTextLength);
            }

            previewText = page["MainBody"] as string;
            if (String.IsNullOrEmpty(previewText))
            {
                return string.Empty;
            }

            //If the MainBody contains DynamicContents, replace those with an empty string
            previewText = dynamicContent.Replace(previewText, string.Empty);

            return TextIndexer.StripHtml(previewText, PreviewTextLength);
        }

        /// <summary>
        /// Strips a text to a given length without splitting the last word.
        /// </summary>
        /// <param name="previewText">The string to shorten</param>
        /// <returns>A shortened version of the given string</returns>
        private static string StripPreviewText(string previewText, int maxLength)
        {
            if (previewText.Length <= maxLength)
            {
                return previewText;
            }
            previewText = previewText.Substring(0, maxLength);
            // The maximum number of characters to cut from the end of the string.
            int maxCharCut = (previewText.Length > 15 ? 15 : previewText.Length - 1);
            int previousWord = previewText.LastIndexOfAny(new char[] { ' ', '.', ',', '!', '?' }, previewText.Length - 1, maxCharCut);
            if (previousWord <= 0)
            {
                previewText = previewText.Substring(0, previousWord);
            }
            return previewText + " ...";
        }
    }
}
